package com.jiuling.apis.service.basic;

import com.jiuling.apis.model.Hmodel.TBaseMerchant;
import com.jiuling.apis.model.Hmodel.TSysUser;
import com.jiuling.apis.model.Pmodel.User;
import com.jswzc.dao.hdao.BaseDaoI;
import com.jswzc.dao.mdao.DaoSupport;
import com.jswzc.framework.util.MD5;
import com.jswzc.framework.util.StringUtil;
import com.jswzc.framework.util.UuidUtil;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by yzljj on 2016/6/23.
 */
@Service("userService")
public class UserServiceImpl implements  UserServiceI {

    @Autowired
    private BaseDaoI<TSysUser> tSysUserDao;
    @Autowired
    private BaseDaoI<TBaseMerchant> tBaseMerchantDao;


    @Resource(name = "daoSupport")
    private DaoSupport dao;


    @Override
    public void doRegist(User user) throws Exception {
        //1 检测用户名 phone是否已经注册

        TSysUser exsitedUser = tSysUserDao.getByHql(StringUtil.formateString("from TSysUser where loginName='{0}' or phone='{1}'", user.getLoginName(), user.getPhone()));
        if (exsitedUser != null && !StringUtil.isNullOrEmpty(exsitedUser.getId())) {
            throw new RuntimeException("该用户或用户名已经存在!");
        }

        if (!user.getPassword().equals(user.getRePassword())) {
            throw new RuntimeException("两次密码不一致!");
        }

        //add base_merchant
        //TBaseMerchant tBaseMerchant = new TBaseMerchant();
        //tBaseMerchant.setIsdel(0);
        //tBaseMerchant.setState(0);
        //tBaseMerchant.setCreateTime(new Date());
        //String merchantId = (String) tBaseMerchantDao.save(tBaseMerchant);

        //创建t_sys_user
        TSysUser tSysUser = new TSysUser();
        tSysUser.setLoginName(user.getLoginName());
        tSysUser.setPhone(user.getPhone());
        tSysUser.setPwd(MD5.md5(user.getPassword()));
        tSysUser.setIsdel((short) 0);
        tSysUser.setCreateTime(new Date());
        tSysUser.setIdentity((short) 2);
        //tSysUser.setIdentityCode(merchantId);
        tSysUserDao.save(tSysUser);

        //user.setId(UuidUtil.get32UUID());
        //user.setIdentity(2);
        //user.setPassword(MD5.md5(user.getPassword()));
        //
        //dao.save("userDao.insertUser",user);


    }

    @Override
    public TSysUser doLogin(User user) throws Exception {
        TSysUser loginUser = tSysUserDao.getByHql(StringUtil.formateString("from TSysUser where pwd='{0}' and (loginName='{1}' or phone='{1}')", MD5.md5(user.getPassword()),user.getLoginName()));
        if (loginUser == null || StringUtil.isNullOrEmpty(loginUser.getId())) {
            throw new RuntimeException("用户名密码不正确!");
        }
        return loginUser;
    }
}
